#include "mysqlite3.h"
#include <string>

using namespace std;

Mysqlite3::Mysqlite3():m_conn(NULL)
{}

Mysqlite3::~Mysqlite3()
{
    release();
}

bool Mysqlite3::create_open(const string& dbname,bool bmutilthread)
{
    release();

    int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    if ( bmutilthread )
        flags |= SQLITE_OPEN_NOMUTEX;

    int ret = sqlite3_open_v2(dbname.c_str(),&m_conn, flags ,NULL);
    if ( ret != SQLITE_OK)
    {
        if ( m_conn != NULL )
            sqlite3_close(m_conn);

        m_conn == NULL;
        return false;
    }
    return true;
}

bool Mysqlite3::open(const string& dbname)
{
    release();
    int ret = sqlite3_open(dbname.c_str(),&m_conn);
    if ( ret != SQLITE_OK)
    {
        if ( m_conn != NULL )
            sqlite3_close(m_conn);

        m_conn == NULL;
        return false;
    }
    return true;
}

bool Mysqlite3::exec(const string& cmd, sqlite3cb cb, string& errmsg,void* relayed_param)
{
    if ( m_conn == NULL || cmd.empty() )
        return false;

    char* perrmsg = NULL;
    int ret = sqlite3_exec(m_conn, cmd.c_str(), cb, relayed_param, &perrmsg);
    if ( perrmsg != NULL )
    {
        errmsg = perrmsg;
        sqlite3_free(perrmsg);
    }

    return ret == SQLITE_OK;
}

void Mysqlite3::release()
{
    if ( m_conn != NULL )
    {
        sqlite3_close(m_conn);
        m_conn = NULL;
    }
}

